<?php
class access {
	protected $access;
	
	const ACCESS	= 1;
	const RECURSIVE	= 2;
	const SUPER		= 4;
	
	public function __construct($user = null)
	{
		if ($user == null)
			$user = new user();
		
		$this->access = array();
		$this->findRight($user->user_id, 'user');
		foreach ($user->GetGroup() as $group)
			$this->findRight($group['id'], 'group');
	}
	
	public function right($path)
	{
		$elements = explode('/', $path);
		$actual = 0;
		$path = '';
		$access = false;
		
		while (isset($elements[$actual]))
		{
			$path .= '/' . $elements[$actual];
			$actual++;

			if (isset($this->access[$path]) && (
				$this->access[$path]['recursive']
				| $actual == count($elements)
			))
			{
				if ($this->access[$path]['super'])
				{
					$access = $this->access[$path]['autorize'];
					break;
				}
				elseif ($this->access[$path]['autorize'])
				{
					$access = true;
				}
			}
			if ($path == '/')
				$path = '';
		}
		return $access;
	}
	
	public function force($path)
	{
		if($this->right($path) === false)
			throw new Error403();
		return true;
	}
	
	protected function findRight($owner, $ownerType)
	{
		$table = new SQL('user_access');
		$list = $table
			->where(array(
				'owner_id' => $owner,
				'owner_type' => $ownerType,
			))
			->select();

		foreach ($list as $right)
		{
			$this->access[$right->access] = array(
				'access_id' => $right->access_id,
				'access' => $right->access,
				'super' => $this->IsFlag(self::SUPER, $right->flags),
				'recursive' => $this->IsFlag(self::RECURSIVE, $right->flags),
				'autorize' => $this->IsFlag(self::ACCESS, $right->flags),
			);
		}
	}
	
	protected function IsFlag($flag, $value)
	{
		return ((int)$flag & (int)$value) != 0;
	}
	
	protected function AddFlag($flag, $value)
	{
		return $flag | $value;
	}
	
	protected function DelFlag($flag, $value)
	{
		return ~$flag & $value;
	}
}